
const qs = require('qs');

const {
    logger,
    sleep,
    lpop,
    get,
} = require('./util');

const {
    syncExec,
} = require('./model'); 

process.on('unhandledRejection', error => {
    logger('unhandledRejection', error)
});

(async () => {

    while (1) {
        const serial = await lpop('ti_worker_order');
        if (!serial) {
            await sleep(1000);
            continue;
        }
        logger('开始下单流程', serial);

        const cookie = await get('ti_worker_cookie');

        //打开购物车页，获取CSRFToken
        let cmdStr = `curl --compressed -H 'Host: www.ti.com.cn' -H 'Connection: keep-alive' -H 'sec-ch-ua: "Google Chrome";v="95", "Chromium";v="95", ";Not A Brand";v="99"'  -H 'sec-ch-ua-mobile: ?0'   -H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36" -H "Cache-Control: max-age=0" -H 'sec-ch-ua-platform: "macOS"' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' -H 'Upgrade-Insecure-Requests: 1' -H 'Sec-Fetch-Site: same-origin' -H 'Sec-Fetch-User: ?1' -H 'Sec-Fetch-Mode: navigate' -H 'Sec-Fetch-Dest: document' -H 'Referer: https://www.ti.com.cn/ordering-resources/buying-tools/quick-add-to-cart.html' -H 'Accept-Encoding: gzip, deflate, br' -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8' -H 'Cookie: ${cookie}' https://www.ti.com.cn/store/ti/zh/cart`;
        let ret = await syncExec(cmdStr);
        if (ret.indexOf('CSRFToken') < 0) {
            logger('无法打开购物车页面获取CSRFToken', ret);
            await sleep(5000);
            continue;
        }
        const CSRFToken = ret.match(/name="CSRFToken" value="([0-9a-zA-Z-]+)"/)[1];
        logger('获取CSRFToken成功', CSRFToken);

        //提交地址
        const step1Data = qs.stringify({
            addressType: 'Business',
            countryIso: 'CN',
            editAddress: 'true',
            addressId: '9015785586711',//不同帐号的地址id不一样
            shippingAddress: 'true',
            firstName: 'Xiaochong',
            lastName: 'Zhang',
            line1: '576, 5 / F, phase I, Huaqiang North',
            line2: 'New Asia, Futian District',
            townCity: 'Shenzhen City',
            state: 'Guangdong Province',
            gstn: '',
            panNumber: '',
            sezCustomer: '',
            postcode: '518000',
            companyName: 'chuangxinrun Electronics Co., Ltd',
            companyUrl: 'http://zxiaocong.hqew.com/',
            gstExemptCert: '',
            pstExemptCert: '',
            qstExemptCert: '',
            taxId: '',
            phoneCountryPrefix: '86-CN',
            phoneNumber: '136 3267 1185',
            phoneExtension: '',
            email: 'cxr228@chuangxinrun.com',
            _saveInAddressBook: 'on',
            middleName2: 'Shenzhen',
            taxExemptValidated: 'false',
            isTaxExempt: 'false',
            same_billingAddress: 'on',
            billingAddress: 'true',
            CSRFToken,
        });
        //注意这里的一些参数跟前面不一样
        cmdStr = `curl --compressed -H 'Host: www.ti.com.cn' -H 'Connection: keep-alive' -H 'sec-ch-ua: "Google Chrome";v="95", "Chromium";v="95", ";Not A Brand";v="99"'  -H 'sec-ch-ua-mobile: ?0'   -H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36" -H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8" -H 'X-Sec-Clge-Req-Type: ajax' -H 'Expires: 0' -H "Cache-Control: no-store, must-revalidate" -H 'sec-ch-ua-platform: "macOS"' -H 'Accept: */*' -H 'Origin: https://www.ti.com.cn' -H 'Sec-Fetch-Site: same-origin' -H 'Sec-Fetch-Mode: cors' -H 'Sec-Fetch-Dest: empty' -H 'Referer: https://www.ti.com.cn/store/ti/zh/checkout/buy/multi/delivery-address/add?storeFlashAtts=true&validPrice=true' -H 'Accept-Encoding: gzip, deflate, br' -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8' -H 'Cookie: ${cookie}' -d '${step1Data}'  https://www.ti.com.cn/store/ti/zh/checkout/buy/multi/delivery-address/addSelected`;
        ret = await syncExec(cmdStr);
        if (ret.indexOf('validated') < 0) {
            logger('提交地址失败', ret);
            await sleep(5000);
            continue;
        } else {
            logger('提交地址成功', ret);
        }

        //确认税单
        const step2Data = qs.stringify({
            id: '',
            type: 'SPECIALPAPERINVOICE',
            recipient: '深圳市创新润电子有限公司',
            vatInvoiceTitleFlag: 'true',
            taxRegistrationNumber: '91440300359713066T',
            registrationAddress: '深圳市福田区华强北街道中航路新亚洲一期5楼576',
            phoneNumber: '075 5825 44500',
            bankName: '中国民生银行华强支行',
            bankAccountNo: '150066364',
            billTo_countryIso: '0',
            'vatInvoiceAddress.firstName': '张晓冲',
            'vatInvoiceAddress.companyName': '深圳市创新润电子有限公司',
            'vatInvoiceAddress.phoneCountryPrefix': '0',
            'vatInvoiceAddress.phoneNumber': '136 3267 1185',
            'vatInvoiceAddress.countryIso': 'CN',
            'vatInvoiceAddress.line1': '深圳市福田区华强北街道中航路新亚洲一期5楼576',
            'vatInvoiceAddress.townCity': '深圳市',
            'vatInvoiceAddress.state': '广东省',
            'vatInvoiceAddress.postcode': '518000',
            phone1: '0',
            mobileNumber: '',
            email: '',
            CSRFToken,
        });
        cmdStr = `curl --compressed -H 'Host: www.ti.com.cn' -H 'Connection: keep-alive' -H 'sec-ch-ua: "Google Chrome";v="95", "Chromium";v="95", ";Not A Brand";v="99"'  -H 'sec-ch-ua-mobile: ?0'   -H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36" -H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8" -H 'X-Sec-Clge-Req-Type: ajax' -H 'Expires: 0' -H "Cache-Control: no-store, must-revalidate" -H 'sec-ch-ua-platform: "macOS"' -H 'Accept: */*' -H 'Origin: https://www.ti.com.cn' -H 'Sec-Fetch-Site: same-origin' -H 'Sec-Fetch-Mode: cors' -H 'Sec-Fetch-Dest: empty' -H 'Referer: https://www.ti.com.cn/store/ti/zh/checkout/multi/cn-tax-invoice' -H 'Accept-Encoding: gzip, deflate, br' -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8' -H 'Cookie: ${cookie}' -d '${step2Data}'  https://www.ti.com.cn/store/ti/zh/checkout/multi/cn-tax-invoice/add`;
        ret = await syncExec(cmdStr);
        logger('确认税单', ret);

        //合规确认
        const step3Data = qs.stringify({
            militaryFlag: 'No',
            eeId: 22565,
            eeName: '游戏控制器和外设',
            appId: 162,
            appName: '游戏',
            selectedIOR: '',
        });
        cmdStr = `curl --compressed -H 'Host: www.ti.com.cn' -H 'Connection: keep-alive' -H 'sec-ch-ua: "Google Chrome";v="95", "Chromium";v="95", ";Not A Brand";v="99"'  -H 'sec-ch-ua-mobile: ?0'   -H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36" -H 'Expires: 0' -H "Cache-Control: no-store, must-revalidate" -H 'sec-ch-ua-platform: "macOS"' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' -H 'Origin: https://www.ti.com.cn' -H 'Sec-Fetch-Site: same-origin' -H 'Sec-Fetch-User: ?1' -H 'Sec-Fetch-Mode: navigate' -H 'Sec-Fetch-Dest: document' -H 'Referer: https://www.ti.com.cn/store/ti/zh/checkout/buy/multi/regulations-step/choose' -H 'Accept-Encoding: gzip, deflate, br' -H 'Upgrade-Insecure-Requests: 1' -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8' -H 'Cookie: ${cookie}'  https://www.ti.com.cn/store/ti/zh/checkout/buy/multi/regulations-step/validate?${step3Data}`;
        ret = await syncExec(cmdStr);
        logger('合规确认', ret);

        //运费确认
        const step4Data = qs.stringify({
            delivery_method: 'v2-china-INT-0_1k-EH',
            termsAccepted: 'Yes',
        });
        cmdStr = `curl --compressed -H 'Host: www.ti.com.cn' -H 'Connection: keep-alive' -H 'sec-ch-ua: "Google Chrome";v="95", "Chromium";v="95", ";Not A Brand";v="99"'  -H 'sec-ch-ua-mobile: ?0'   -H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36" -H 'Expires: 0' -H "Cache-Control: no-store, must-revalidate" -H 'sec-ch-ua-platform: "macOS"' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' -H 'Origin: https://www.ti.com.cn' -H 'Sec-Fetch-Site: same-origin' -H 'Sec-Fetch-User: ?1' -H 'Sec-Fetch-Mode: navigate' -H 'Sec-Fetch-Dest: document' -H 'Referer: https://www.ti.com.cn/store/ti/zh/checkout/buy/multi/delivery-method/choose' -H 'Accept-Encoding: gzip, deflate, br' -H 'Upgrade-Insecure-Requests: 1' -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8' -H 'Cookie: ${cookie}'  https://www.ti.com.cn/store/ti/zh/checkout/buy/multi/delivery-method/select?${step4Data}`;
        ret = await syncExec(cmdStr);
        logger('运费确认', ret);

        //提交订单
        const step5Data = qs.stringify({
            paymentMethod: 'unionpay_b',
            CSRFToken,
        });
        cmdStr = `curl --compressed -H 'Host: www.ti.com.cn' -H 'Connection: keep-alive' -H 'sec-ch-ua: "Google Chrome";v="95", "Chromium";v="95", ";Not A Brand";v="99"'  -H 'sec-ch-ua-mobile: ?0'   -H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36" -H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8" -H 'X-Sec-Clge-Req-Type: ajax' -H 'Expires: 0' -H "Cache-Control: no-store, must-revalidate" -H 'sec-ch-ua-platform: "macOS"' -H 'Accept: */*' -H 'Origin: https://www.ti.com.cn' -H 'Sec-Fetch-Site: same-origin' -H 'Sec-Fetch-Mode: cors' -H 'Sec-Fetch-Dest: empty' -H 'Referer: https://www.ti.com.cn/store/ti/zh/checkout/buy/multi/payment-method/add' -H 'Accept-Encoding: gzip, deflate, br' -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8' -H 'Cookie: ${cookie}' -d '${step5Data}'  https://www.ti.com.cn/store/ti/zh/checkout/buy/multi/payment-method/citcon/addSelectedPayment`;
        ret = await syncExec(cmdStr);
        logger('提交订单', ret);
        const tmp = ret.match(/T\d{6,9}/);
        if (tmp && tmp[0]) {
            const orderId = tmp[0];
            logger('提交订单成功！', orderId);
        } else {
            logger('提交订单失败');
        }

        await sleep(10000);
    }

})();

